<script setup lang="tsx">
// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 模块导入 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

import { computed, nextTick, reactive, ref, shallowRef, watch } from 'vue';
import type { TreeOption } from 'naive-ui';
import dayjs from 'dayjs';
import { $t } from '@/locales';
import { useAuth } from '@/hooks/business/auth';
import { useDict } from '@/hooks/business/dict';
import { useNaiveForm } from '@/hooks/common/form';
import { fetchAddDmApply, fetchGetDmApply, fetchGetMyUniqueProvinceCityCounty, fetchGetOrgUnitTree, fetchUpdateDmApply } from '@/service/api';
import { TreeUtil } from '@/utils/z';

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 组件名称 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

defineOptions({
  name: 'DmApplyOperateModal'
});

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 组合式函数 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

const { validate, restoreValidation } = useNaiveForm();

const { currentOrgPosition, userInfo } = useAuth();

const { dictOptions, dictLabel } = useDict();

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 父子传参 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

interface Props {
  operateType: OperateType;
  rowData?: Api.Dimo.Apply | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 框架模型 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

export type OperateType = NaiveUI.TableOperateType | 'view';

const isAdd = computed(() => props.operateType === 'add');

const isEdit = computed(() => props.operateType === 'edit');

const isView = computed(() => props.operateType === 'view');

const addKey = computed(() => `DMAPPLY${userInfo()?.userName}ADD`);

const editKey = computed(() => `DMAPPLY${userInfo()?.userName}EDIT${props.rowData?.id}`);

/** 页面标题 */
const title = computed(() => {
  const titles: Record<OperateType, string> = {
    add: $t('common.add'),
    edit: $t('common.edit'),
    view: '查看'
  };
  return `【${titles[props.operateType]}】主要覆膜作物农用薄膜应用情况调查表`;
});

type Model = Api.Dimo.Apply;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    id: '',
    createUser: '',
    createTime: '',
    updateUser: '',
    updateTime: '',
    tenantId: '',
    orgId: '',
    positionId: '',
    reportUnit: '',
    reportDate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    reportPerson: '',
    reportPersonContactInfo: '',
    investPerson: '',
    investPersonContactInfo: '',
    countyAuthStatus: false,
    countyAuthDate: '',
    countyAuthUserId: 0,
    cityAuthStatus: false,
    cityAuthDate: '',
    cityAuthUserId: 0,
    provinceAuthStatus: false,
    provinceAuthDate: '',
    provinceAuthUserId: 0,
    comment: '',
    provinceCityCountyInfo: {
      provinceId: '',
      provinceName: '',
      cityId: '',
      cityName: '',
      countyId: '',
      countyName: ''
    },
    applyDetails: [createApplyCounty()]
  };
}

function createApplyCounty(): Api.Dimo.DmApplyCounty {
  return {
    countyId: '',
    pmApplyDetails: [createApplyDetail()],
    dmApplyDetails: [createApplyDetail()]
  };
}

function createApplyDetail(): Api.Dimo.ApplyDetail {
  return {
    id: '',
    createUser: '',
    createTime: '',
    updateUser: '',
    updateTime: '',
    tenantId: '',
    applyId: '',
    countyId: '',
    cropDictCode: '',
    cropDictItemCode: '',
    plantArea: 0,
    coverTotal: 0,
    coverStandard: 0,
    coverThick: 0,
    coverDegrade: 0,
    useTotal: 0,
    useStandard: 0,
    useThick: 0,
    useDegrade: 0,
    comment: ''
  };
}

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 业务模型 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

const orgType = ref<string>(currentOrgPosition()?.orgType || '');

const orgTreeOptions = shallowRef<TreeOption[]>([]);

const showTable = ref<boolean>(true);

const isCountyOperate = computed(
  () => (isAdd.value && orgType.value === 'County') || TreeUtil.findNodeInTree(orgTreeOptions.value, model.provinceCityCountyInfo.countyId)
);

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 框架方法 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

/** 模型初始化 */
function handleInitModel() {
  Object.assign(model, createDefaultModel());

  fetchGetOrgUnitTree().then(({ error, data }) => {
    if (!error && data) {
      orgTreeOptions.value = data.map(toTreeOptionNode);
    }
  });

  let localData = null;
  if (props.operateType === 'add') {
    localData = localStorage.getItem(addKey.value);
  } else if (props.operateType === 'edit') {
    localData = localStorage.getItem(editKey.value);
  }

  if (localData) {
    window.$dialog?.info({
      title: $t('common.tip'),
      content: '检测到上次您有未保存的数据，是否继续使用该数据进行操作?',
      positiveText: $t('common.confirm'),
      negativeText: $t('common.cancel'),
      onPositiveClick: () => {
        showTable.value = false;
        nextTick(() => {
          Object.assign(model, JSON.parse(localData));
          showTable.value = true;
        });
      },
      onNegativeClick: () => {
        if (isAdd.value) {
          localStorage.removeItem(addKey.value);
        } else if (isEdit.value) {
          localStorage.removeItem(editKey.value);
        }
        handleAEV();
      }
    });
  } else {
    handleAEV();
  }
}

function handleAEV() {
  if (props.operateType === 'add') {
    model.reportPerson = userInfo()?.realName || '';
    fetchGetMyUniqueProvinceCityCounty().then(({ error, data }) => {
      if (!error && data) {
        model.provinceCityCountyInfo = data;
        model.orgId = data.countyId ?? data.cityId ?? data.provinceId;
      }
    });
  } else if (['edit', 'view'].includes(props.operateType) && props.rowData) {
    showTable.value = false;
    fetchGetDmApply(props.rowData?.id || '').then(({ error, data }) => {
      if (!error && data) {
        data.reportDate = dayjs(data.reportDate).format('YYYY-MM-DD HH:mm:ss');
        Object.assign(model, data);
        showTable.value = true;
      }
    });
  }
}

function closeModal() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  const func = isAdd.value ? fetchAddDmApply : fetchUpdateDmApply;
  if (isAdd.value) {
    model.orgId = currentOrgPosition()?.orgId || '';
    model.positionId = currentOrgPosition()?.positionId || '';
  }
  const { error, data } = await func(model);
  if (!error && data) {
    window.$message?.success(isAdd.value ? $t('common.addSuccess') : $t('common.updateSuccess'));
    if (isAdd.value) {
      localStorage.removeItem(addKey.value);
    } else if (isEdit.value) {
      localStorage.removeItem(editKey.value);
    }
    closeModal();
    emit('submitted');
  }
}

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 业务方法 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

function toTreeOptionNode(item: Api.SystemManage.OrgUnitTree): TreeOption {
  const option: TreeOption = {
    key: item.id,
    label: item.name,
    disabled: item.orgType !== 'County'
  };
  if (item.children && item.children.length > 0) {
    option.children = item.children.map(toTreeOptionNode);
  }
  return option;
}

/** 新增县 */
function plusCounty(index: number, type: string) {
  if (type === 'push') {
    model.applyDetails.push(createApplyCounty());
  } else {
    model.applyDetails.splice(index + 1, 0, createApplyCounty());
  }
}

/** 删除县 */
function reduceCounty(index: number) {
  model.applyDetails.splice(index, 1);
}

/** 上移县 */
function upCounty(index: number) {
  showTable.value = false;
  nextTick(() => {
    const element = model.applyDetails.splice(index, 1)[0];
    model.applyDetails.splice(index - 1, 0, element);
    showTable.value = true;
  });
}

/** 下移县 */
function downCounty(index: number) {
  showTable.value = false;
  nextTick(() => {
    const element = model.applyDetails.splice(index, 1)[0];
    model.applyDetails.splice(index + 1, 0, element);
    showTable.value = true;
  });
}

/** 新增棚膜作物 */
function plusPm(rows: Api.Dimo.ApplyDetail[], index: number, type: string) {
  if (type === 'push') {
    rows.push(createApplyDetail());
  } else {
    rows.splice(index + 1, 0, createApplyDetail());
  }
}

/** 删除棚膜作物 */
function reducePm(rows: Api.Dimo.ApplyDetail[], index: number) {
  rows.splice(index, 1);
}

/** 新增地膜作物 */
function plusDm(rows: Api.Dimo.ApplyDetail[], index: number, type: string) {
  if (type === 'push') {
    rows.push(createApplyDetail());
  } else {
    rows.splice(index + 1, 0, createApplyDetail());
  }
}

/** 删除地膜作物 */
function reduceDm(rows: Api.Dimo.ApplyDetail[], index: number) {
  rows.splice(index, 1);
}

/** 表格滚动事件 */
const originalTableRef = ref();
const floatingTableRef = ref();
const lastScrollHeight = ref<number>(0);
function handleTableScroll() {
  const tableContainer = originalTableRef.value.parentNode;
  const scrollTop = tableContainer.scrollTop;
  if (lastScrollHeight.value === 0 && scrollTop > 1) {
    lastScrollHeight.value = scrollTop;
    const theadClone = originalTableRef.value.querySelector('thead').cloneNode(true);
    floatingTableRef.value.appendChild(theadClone);
    const originalHeaders = originalTableRef.value.querySelectorAll('th');
    const floatingHeaders = floatingTableRef.value.querySelectorAll('th');
    originalHeaders.forEach((header: any, index: any) => {
      floatingHeaders[index].style.width = `${header.offsetWidth}px`;
    });
    floatingTableRef.value.style.top = `${scrollTop}px`;
    floatingTableRef.value.style.display = 'table';
  } else if (lastScrollHeight.value !== 0 && scrollTop === 0) {
    lastScrollHeight.value = scrollTop;
    floatingTableRef.value.style.top = `${scrollTop}px`;
    floatingTableRef.value.innerHTML = '';
    floatingTableRef.value.style.display = 'none';
  } else if (lastScrollHeight.value !== 0 && scrollTop !== 0) {
    lastScrollHeight.value = scrollTop;
    floatingTableRef.value.style.top = `${scrollTop}px`;
  }
}

function tempSave() {
  if (isAdd.value) {
    localStorage.removeItem(addKey.value);
    const plainObject = JSON.parse(JSON.stringify(model));
    localStorage.setItem(addKey.value, JSON.stringify(plainObject));
  } else if (isEdit.value) {
    const plainObject = JSON.parse(JSON.stringify(model));
    localStorage.setItem(editKey.value, JSON.stringify(plainObject));
  }
  window.$message?.success('临时保存成功');
}

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 框架生命周期 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

/** 监听页面初始化 */
watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 业务生命周期 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

// ---------- 页面统计 ----------

// 县合计
const countyCount = ref<Map<string, Api.Dimo.ApplyDetail>>(new Map());
// 市棚膜合计
const cityPmDetails = ref<Api.Dimo.ApplyDetail[]>([]);
// 市地膜合计
const cityDmDetails = ref<Api.Dimo.ApplyDetail[]>([]);
// 市合计
const cityCount = ref<Api.Dimo.ApplyDetail>(createApplyDetail());
watch(
  () => model.applyDetails,
  () => {
    const countyCount1 = new Map();
    const cityPmDetailMap1: Map<string, Api.Dimo.ApplyDetail> = new Map();
    const cityDmDetailMap1: Map<string, Api.Dimo.ApplyDetail> = new Map();
    const cityCount1 = createApplyDetail();
    model.applyDetails.forEach(county => {
      countyCount1.set(county.countyId, createApplyDetail());
      county.pmApplyDetails.forEach(pm => {
        if (pm.cropDictItemCode !== '') {
          const item1 = countyCount1.get(county.countyId);
          item1.plantArea += pm.plantArea;
          item1.coverTotal += pm.coverTotal;
          item1.coverStandard += pm.coverStandard;
          item1.coverThick += pm.coverThick;
          item1.coverDegrade += pm.coverDegrade;
          item1.useTotal += pm.useTotal;
          item1.useStandard += pm.useStandard;
          item1.useThick += pm.useThick;
          item1.useDegrade += pm.useDegrade;

          if (!cityPmDetailMap1.has(pm.cropDictItemCode)) {
            cityPmDetailMap1.set(pm.cropDictItemCode, createApplyDetail());
          }

          const item2 = cityPmDetailMap1.get(pm.cropDictItemCode)!;
          item2.cropDictItemCode = pm.cropDictItemCode;
          item2.plantArea += pm.plantArea;
          item2.coverTotal += pm.coverTotal;
          item2.coverStandard += pm.coverStandard;
          item2.coverThick += pm.coverThick;
          item2.coverDegrade += pm.coverDegrade;
          item2.useTotal += pm.useTotal;
          item2.useStandard += pm.useStandard;
          item2.useThick += pm.useThick;
          item2.useDegrade += pm.useDegrade;

          cityCount1.plantArea += pm.plantArea;
          cityCount1.coverTotal += pm.coverTotal;
          cityCount1.coverStandard += pm.coverStandard;
          cityCount1.coverThick += pm.coverThick;
          cityCount1.coverDegrade += pm.coverDegrade;
          cityCount1.useTotal += pm.useTotal;
          cityCount1.useStandard += pm.useStandard;
          cityCount1.useThick += pm.useThick;
          cityCount1.useDegrade += pm.useDegrade;
        }
      });
      county.dmApplyDetails.forEach(dm => {
        if (dm.cropDictItemCode !== '') {
          const item1 = countyCount1.get(county.countyId);
          item1.plantArea += dm.plantArea;
          item1.coverTotal += dm.coverTotal;
          item1.coverStandard += dm.coverStandard;
          item1.coverThick += dm.coverThick;
          item1.coverDegrade += dm.coverDegrade;
          item1.useTotal += dm.useTotal;
          item1.useStandard += dm.useStandard;
          item1.useThick += dm.useThick;
          item1.useDegrade += dm.useDegrade;

          if (!cityDmDetailMap1.has(dm.cropDictItemCode)) {
            cityDmDetailMap1.set(dm.cropDictItemCode, createApplyDetail());
          }

          const item2 = cityDmDetailMap1.get(dm.cropDictItemCode)!;
          item2.cropDictItemCode = dm.cropDictItemCode;
          item2.plantArea += dm.plantArea;
          item2.coverTotal += dm.coverTotal;
          item2.coverStandard += dm.coverStandard;
          item2.coverThick += dm.coverThick;
          item2.coverDegrade += dm.coverDegrade;
          item2.useTotal += dm.useTotal;
          item2.useStandard += dm.useStandard;
          item2.useThick += dm.useThick;
          item2.useDegrade += dm.useDegrade;

          cityCount1.plantArea += dm.plantArea;
          cityCount1.coverTotal += dm.coverTotal;
          cityCount1.coverStandard += dm.coverStandard;
          cityCount1.coverThick += dm.coverThick;
          cityCount1.coverDegrade += dm.coverDegrade;
          cityCount1.useTotal += dm.useTotal;
          cityCount1.useStandard += dm.useStandard;
          cityCount1.useThick += dm.useThick;
          cityCount1.useDegrade += dm.useDegrade;
        }
      });
    });
    countyCount.value = countyCount1;
    const list1 = [];
    for (const value of cityPmDetailMap1.values()) {
      list1.push(value);
    }
    if (list1.length === 0) {
      list1.push(createApplyDetail());
    }
    const list2 = [];
    for (const value of cityDmDetailMap1.values()) {
      list2.push(value);
    }
    if (list2.length === 0) {
      list2.push(createApplyDetail());
    }
    cityPmDetails.value = list1;
    cityDmDetails.value = list2;
    cityCount.value = cityCount1;
  },
  { deep: true }
);
</script>

<template>
  <NModal
    v-model:show="visible"
    class="modal-container"
    :style="{ width: 'calc(100vw - 20px)' }"
    :title="title"
    preset="card"
    :close-on-esc="false"
    :mask-closable="false"
  >
    <div class="mb-12px">
      <NGrid v-if="!isView" x-gap="12" :cols="isCountyOperate ? 4 : 3">
        <NGi>
          <NInput v-model:value="model.reportUnit" type="text">
            <template #prefix>填报单位：</template>
          </NInput>
        </NGi>
        <NGi>
          <NInput v-model:value="model.provinceCityCountyInfo.cityName" type="text" disabled>
            <template #prefix>市：</template>
          </NInput>
        </NGi>
        <NGi v-if="isCountyOperate">
          <NInput v-model:value="model.provinceCityCountyInfo.countyName" type="text" disabled>
            <template #prefix>县：</template>
          </NInput>
        </NGi>
        <NGi>
          <NDatePicker v-model:formatted-value="model.reportDate" type="date" value-format="yyyy-MM-dd HH:mm:ss" :disabled="isView" />
        </NGi>
      </NGrid>
      <NSpace v-else>
        <span class="mr-60px">
          <b>填报单位：</b>
          {{ model.reportUnit }}
        </span>
        <span class="mr-60px">
          <b>市：</b>
          {{ model.provinceCityCountyInfo.cityName }}
        </span>
        <span v-if="isCountyOperate" class="mr-60px">
          <b>县：</b>
          {{ model.provinceCityCountyInfo.countyName }}
        </span>
        <span>
          <b>填报日期：</b>
          {{ dayjs(model.reportDate).format('YYYY-MM-DD') }}
        </span>
      </NSpace>
    </div>
    <div class="table-container relative mb-12px overflow-y-scroll" :class="{ 'view-h': isView }" @scroll="handleTableScroll">
      <table ref="floatingTableRef" class="absolute left-0 z-999"></table>
      <table ref="originalTableRef">
        <thead>
          <tr>
            <th rowspan="2" class="w-220px">
              县
              <br />
              （市、区）
            </th>
            <th colspan="2" rowspan="2">
              作物
              <br />
              类型
            </th>
            <th rowspan="2" class="w-120px">
              种植面积
              <br />
              （亩）
            </th>
            <th colspan="4">覆盖面积（亩）</th>
            <th colspan="4">使用量（千克）</th>
            <th rowspan="2" class="w-120px">备注</th>
            <th rowspan="2" class="w-120px">操作</th>
          </tr>
          <tr>
            <th class="w-120px">覆盖面积</th>
            <th class="w-120px">
              其中,
              <br />
              标准地膜
            </th>
            <th class="w-120px">
              其中, 加厚
              <br />
              高强度地膜
            </th>
            <th class="w-120px">
              其中, 全生
              <br />
              物降解地膜
            </th>
            <th class="w-120px">使用量</th>
            <th class="w-120px">
              其中,
              <br />
              标准地膜
            </th>
            <th class="w-120px">
              其中, 加厚
              <br />
              高强度地膜
            </th>
            <th class="w-120px">
              其中, 全生
              <br />
              物降解地膜
            </th>
          </tr>
        </thead>
        <tbody v-if="showTable">
          <template v-for="(county, county_index) in model.applyDetails" :key="`county_${county_index}`">
            <tr v-for="(pm, pm_index) in county.pmApplyDetails" :key="`pm_${pm_index}`" class="bg-[#f5f5f5]">
              <td v-if="pm_index === 0" :rowspan="county.pmApplyDetails.length + county.dmApplyDetails.length">
                <NTreeSelect
                  v-if="!isView"
                  :options="orgTreeOptions"
                  :default-value="county.countyId"
                  size="small"
                  @update:value="
                    value => {
                      county.countyId = value;
                    }
                  "
                />
                <span v-else>{{ TreeUtil.findNodeInTree(orgTreeOptions, county.countyId)?.label }}</span>
                <NSpace v-if="!isView && ['City'].includes(orgType)" class="mt-12px">
                  <NButton
                    ghost
                    circle
                    type="primary"
                    size="tiny"
                    @click="() => plusCounty(county_index, county_index === model.applyDetails.length - 1 ? 'push' : 'insert')"
                  >
                    <template #icon>
                      <icon-carbon:add />
                    </template>
                  </NButton>
                  <NButton v-if="model.applyDetails.length > 1" ghost circle type="primary" size="tiny" @click="() => reduceCounty(county_index)">
                    <template #icon>
                      <icon-carbon:close />
                    </template>
                  </NButton>
                  <NButton v-if="county_index > 0" ghost circle type="error" size="tiny" @click="() => upCounty(county_index)">
                    <template #icon>
                      <icon-carbon:arrow-up />
                    </template>
                  </NButton>
                  <NButton
                    v-if="county_index < model.applyDetails.length - 1"
                    ghost
                    circle
                    type="error"
                    size="tiny"
                    @click="() => downCounty(county_index)"
                  >
                    <template #icon>
                      <icon-carbon:arrow-down />
                    </template>
                  </NButton>
                </NSpace>
              </td>
              <td v-if="pm_index === 0" class="w-50px" :rowspan="county.pmApplyDetails.length">
                棚膜
                <br />
                作物
              </td>
              <td v-if="!isView" class="w-160px">
                <NSelect
                  v-if="visible"
                  v-model:value="pm.cropDictItemCode"
                  :disabled="isView"
                  :options="dictOptions('dm_pm_crop')"
                  clearable
                  size="small"
                />
              </td>
              <td v-else>{{ dictLabel('dm_pm_crop', pm.cropDictItemCode) }}</td>
              <td v-if="!isView"><NInputNumber v-model:value="pm.plantArea" clearable :precision="2" :show-button="false" size="small" /></td>
              <td v-else class="text-right">{{ pm.plantArea }}</td>
              <td v-if="!isView"><NInputNumber v-model:value="pm.coverTotal" clearable :precision="2" :show-button="false" size="small" /></td>
              <td v-else class="text-right">{{ pm.coverTotal }}</td>
              <td v-if="!isView"><NInputNumber v-model:value="pm.coverStandard" clearable :precision="2" :show-button="false" size="small" /></td>
              <td v-else class="text-right">{{ pm.coverStandard }}</td>
              <td v-if="!isView"><NInputNumber v-model:value="pm.coverThick" clearable :precision="2" :show-button="false" size="small" /></td>
              <td v-else class="text-right">{{ pm.coverThick }}</td>
              <td v-if="!isView"><NInputNumber v-model:value="pm.coverDegrade" clearable :precision="2" :show-button="false" size="small" /></td>
              <td v-else class="text-right">{{ pm.coverDegrade }}</td>
              <td v-if="!isView"><NInputNumber v-model:value="pm.useTotal" clearable :precision="2" :show-button="false" size="small" /></td>
              <td v-else class="text-right">{{ pm.useTotal }}</td>
              <td v-if="!isView"><NInputNumber v-model:value="pm.useStandard" clearable :precision="2" :show-button="false" size="small" /></td>
              <td v-else class="text-right">{{ pm.useStandard }}</td>
              <td v-if="!isView"><NInputNumber v-model:value="pm.useThick" clearable :precision="2" :show-button="false" size="small" /></td>
              <td v-else class="text-right">{{ pm.useThick }}</td>
              <td v-if="!isView"><NInputNumber v-model:value="pm.useDegrade" clearable :precision="2" :show-button="false" size="small" /></td>
              <td v-else class="text-right">{{ pm.useDegrade }}</td>
              <td v-if="!isView"><NInput v-model:value="pm.comment" clearable :precision="2" :show-button="false" type="text" size="small" /></td>
              <td v-else>{{ pm.comment }}</td>
              <td>
                <NSpace v-if="!isView" justify="center">
                  <NButton
                    ghost
                    circle
                    type="primary"
                    size="tiny"
                    @click="plusPm(county.pmApplyDetails, pm_index, pm_index + 1 === county.pmApplyDetails.length ? 'push' : 'insert')"
                  >
                    <template #icon>
                      <icon-carbon:add />
                    </template>
                  </NButton>
                  <NButton
                    v-if="county.pmApplyDetails.length > 1"
                    ghost
                    circle
                    type="primary"
                    size="tiny"
                    @click="reducePm(county.pmApplyDetails, pm_index)"
                  >
                    <template #icon>
                      <icon-carbon:close />
                    </template>
                  </NButton>
                </NSpace>
              </td>
            </tr>
            <tr v-for="(row2, index2) in county.dmApplyDetails" :key="`dm_${index2}`" class="bg-[#f5f5f5]">
              <td v-if="index2 === 0" :rowspan="county.dmApplyDetails.length">
                露天
                <br />
                覆膜
                <br />
                作物
                <br />
              </td>
              <td v-if="!isView">
                <NSelect v-if="visible" v-model:value="row2.cropDictItemCode" :options="dictOptions('dm_open_air_crop')" size="small" clearable />
              </td>
              <td v-else>{{ dictLabel('dm_open_air_crop', row2.cropDictItemCode) }}</td>
              <td v-if="!isView"><NInputNumber v-model:value="row2.plantArea" clearable :precision="2" :show-button="false" size="small" /></td>
              <td v-else class="text-right">{{ row2.plantArea }}</td>
              <td v-if="!isView"><NInputNumber v-model:value="row2.coverTotal" clearable :precision="2" :show-button="false" size="small" /></td>
              <td v-else class="text-right">{{ row2.coverTotal }}</td>
              <td v-if="!isView"><NInputNumber v-model:value="row2.coverStandard" clearable :precision="2" :show-button="false" size="small" /></td>
              <td v-else class="text-right">{{ row2.coverStandard }}</td>
              <td v-if="!isView"><NInputNumber v-model:value="row2.coverThick" clearable :precision="2" :show-button="false" size="small" /></td>
              <td v-else class="text-right">{{ row2.coverThick }}</td>
              <td v-if="!isView"><NInputNumber v-model:value="row2.coverDegrade" clearable :precision="2" :show-button="false" size="small" /></td>
              <td v-else class="text-right">{{ row2.coverDegrade }}</td>
              <td v-if="!isView"><NInputNumber v-model:value="row2.useTotal" clearable :precision="2" :show-button="false" size="small" /></td>
              <td v-else class="text-right">{{ row2.useTotal }}</td>
              <td v-if="!isView"><NInputNumber v-model:value="row2.useStandard" clearable :precision="2" :show-button="false" size="small" /></td>
              <td v-else class="text-right">{{ row2.useStandard }}</td>
              <td v-if="!isView"><NInputNumber v-model:value="row2.useThick" clearable :precision="2" :show-button="false" size="small" /></td>
              <td v-else class="text-right">{{ row2.useThick }}</td>
              <td v-if="!isView"><NInputNumber v-model:value="row2.useDegrade" clearable :precision="2" :show-button="false" size="small" /></td>
              <td v-else class="text-right">{{ row2.useDegrade }}</td>
              <td v-if="!isView"><NInput v-model:value="row2.comment" clearable :precision="2" :show-button="false" type="text" size="small" /></td>
              <td v-else>{{ row2.comment }}</td>
              <td>
                <NSpace v-if="!isView" justify="center">
                  <NButton
                    ghost
                    circle
                    type="primary"
                    size="tiny"
                    @click="plusDm(county.dmApplyDetails, index2, index2 + 1 === county.dmApplyDetails.length ? 'push' : 'insert')"
                  >
                    <template #icon>
                      <icon-carbon:add />
                    </template>
                  </NButton>
                  <NButton
                    v-if="county.dmApplyDetails.length > 1"
                    ghost
                    circle
                    type="primary"
                    size="tiny"
                    @click="reduceDm(county.dmApplyDetails, index2)"
                  >
                    <template #icon>
                      <icon-carbon:close />
                    </template>
                  </NButton>
                </NSpace>
              </td>
            </tr>
            <tr class="bg-[#fedb61]">
              <td colspan="3">{{ TreeUtil.findNodeInTree(orgTreeOptions, county.countyId)?.label }} 合计</td>
              <td class="text-right">{{ countyCount.get(county.countyId)?.plantArea }}</td>
              <td class="text-right">{{ countyCount.get(county.countyId)?.coverTotal }}</td>
              <td class="text-right">{{ countyCount.get(county.countyId)?.coverStandard }}</td>
              <td class="text-right">{{ countyCount.get(county.countyId)?.coverThick }}</td>
              <td class="text-right">{{ countyCount.get(county.countyId)?.coverDegrade }}</td>
              <td class="text-right">{{ countyCount.get(county.countyId)?.useTotal }}</td>
              <td class="text-right">{{ countyCount.get(county.countyId)?.useStandard }}</td>
              <td class="text-right">{{ countyCount.get(county.countyId)?.useThick }}</td>
              <td class="text-right">{{ countyCount.get(county.countyId)?.useDegrade }}</td>
              <td colspan="2" class="text-center">-</td>
            </tr>
          </template>
          <template v-if="!isCountyOperate">
            <tr v-for="(pm, index) in cityPmDetails" :key="`city_pm_${index}`">
              <td v-if="index === 0" :rowspan="cityDmDetails.length + cityPmDetails.length">{{ model.provinceCityCountyInfo.cityName }}</td>
              <td v-if="index === 0" :rowspan="cityPmDetails.length">
                棚膜
                <br />
                作物
              </td>
              <td>{{ dictLabel('dm_pm_crop', pm.cropDictItemCode) }}</td>
              <td class="text-right">{{ pm.cropDictItemCode !== '' ? pm.plantArea : '' }}</td>
              <td class="text-right">{{ pm.cropDictItemCode !== '' ? pm.coverTotal : '' }}</td>
              <td class="text-right">{{ pm.cropDictItemCode !== '' ? pm.coverStandard : '' }}</td>
              <td class="text-right">{{ pm.cropDictItemCode !== '' ? pm.coverThick : '' }}</td>
              <td class="text-right">{{ pm.cropDictItemCode !== '' ? pm.coverDegrade : '' }}</td>
              <td class="text-right">{{ pm.cropDictItemCode !== '' ? pm.useTotal : '' }}</td>
              <td class="text-right">{{ pm.cropDictItemCode !== '' ? pm.useStandard : '' }}</td>
              <td class="text-right">{{ pm.cropDictItemCode !== '' ? pm.useThick : '' }}</td>
              <td class="text-right">{{ pm.cropDictItemCode !== '' ? pm.useDegrade : '' }}</td>
              <td colspan="2" class="text-center">-</td>
            </tr>
            <tr v-for="(dm, index) in cityDmDetails" :key="`city_dm_${index}`">
              <td v-if="index === 0" :rowspan="cityDmDetails.length">
                露天
                <br />
                覆膜
                <br />
                作物
              </td>
              <td class="text-left">{{ dictLabel('dm_open_air_crop', dm.cropDictItemCode) }}</td>
              <td class="text-right">{{ dm.cropDictItemCode !== '' ? dm.plantArea : '' }}</td>
              <td class="text-right">{{ dm.cropDictItemCode !== '' ? dm.coverTotal : '' }}</td>
              <td class="text-right">{{ dm.cropDictItemCode !== '' ? dm.coverStandard : '' }}</td>
              <td class="text-right">{{ dm.cropDictItemCode !== '' ? dm.coverThick : '' }}</td>
              <td class="text-right">{{ dm.cropDictItemCode !== '' ? dm.coverDegrade : '' }}</td>
              <td class="text-right">{{ dm.cropDictItemCode !== '' ? dm.useTotal : '' }}</td>
              <td class="text-right">{{ dm.cropDictItemCode !== '' ? dm.useStandard : '' }}</td>
              <td class="text-right">{{ dm.cropDictItemCode !== '' ? dm.useThick : '' }}</td>
              <td class="text-right">{{ dm.cropDictItemCode !== '' ? dm.useDegrade : '' }}</td>
              <td colspan="2" class="text-center">-</td>
            </tr>
            <tr class="bg-[#fedb61]">
              <td colspan="3">{{ TreeUtil.findNodeInTree(orgTreeOptions, model.provinceCityCountyInfo.cityId)?.label }} 合计</td>
              <td class="text-right">{{ cityCount.plantArea }}</td>
              <td class="text-right">{{ cityCount.coverTotal }}</td>
              <td class="text-right">{{ cityCount.coverStandard }}</td>
              <td class="text-right">{{ cityCount.coverThick }}</td>
              <td class="text-right">{{ cityCount.coverDegrade }}</td>
              <td class="text-right">{{ cityCount.useTotal }}</td>
              <td class="text-right">{{ cityCount.useStandard }}</td>
              <td class="text-right">{{ cityCount.useThick }}</td>
              <td class="text-right">{{ cityCount.useDegrade }}</td>
              <td colspan="2" class="text-center">-</td>
            </tr>
          </template>
        </tbody>
      </table>
    </div>
    <div class="foot-info">
      <NGrid v-if="!isView" x-gap="12" :cols="4">
        <NGi>
          <NInput v-model:value="model.reportPerson" :disabled="isView">
            <template #prefix>填报人：</template>
          </NInput>
        </NGi>
        <NGi>
          <NInput v-model:value="model.reportPersonContactInfo" :disabled="isView">
            <template #prefix>联系方式：</template>
          </NInput>
        </NGi>
        <NGi>
          <NInput v-model:value="model.investPerson" :disabled="isView">
            <template #prefix>调查员：</template>
          </NInput>
        </NGi>
        <NGi>
          <NInput v-model:value="model.investPersonContactInfo" :disabled="isView">
            <template #prefix>联系方式：</template>
          </NInput>
        </NGi>
      </NGrid>
      <NSpace v-else>
        <span class="mr-60px">
          <b>填报人：</b>
          {{ model.reportPerson }}
        </span>
        <span class="mr-60px">
          <b>联系方式：</b>
          {{ model.reportPersonContactInfo }}
        </span>
        <span class="mr-60px">
          <b>调查员：</b>
          {{ model.investPerson }}
        </span>
        <span>
          <b>联系方式：</b>
          {{ model.investPersonContactInfo }}
        </span>
      </NSpace>
      <div class="h-12px"></div>
      <NInput v-if="!isView" v-model:value="model.comment" type="textarea" placeholder="备注" :disabled="isView" />
      <span v-else>
        <b>备注：</b>
        {{ model.comment }}
      </span>
    </div>
    <template #footer>
      <NSpace v-if="!isView" justify="end">
        <NButton type="warning" @click="tempSave">临时保存</NButton>
        <NButton type="error" @click="closeModal">
          {{ $t('common.cancel') }}
        </NButton>
        <NButton type="primary" @click="handleSubmit">
          {{ $t('common.save') }}
        </NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style lang="scss" scoped>
.table-container {
  border: 1px solid #e5e7eb;
  margin-bottom: 12px;
  height: calc(100vh - 322px);

  &.view-h {
    height: calc(100vh - 198px);
  }

  table {
    width: 100%;
    border-collapse: collapse;

    th,
    td {
      border: 1px solid #e5e7eb;
    }

    thead {
      background-color: #fff;

      tr {
        &:first-child {
          th {
            border-top-width: 0px;
          }
        }
      }
    }

    thead,
    tbody {
      tr {
        th,
        td {
          padding: 5px;

          &:first-child {
            border-left-width: 0px;
          }
        }
      }
    }
  }
}
</style>
